<template>
  <basic-container>
    <el-row>
      <el-col :span="13">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          :page.sync="page"
          :search.sync="query"
          :permission="permissionList"
          :before-open="beforeOpen"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @row-click="rowClick"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.smttable_delete" @click="handleDelete()">删 除 </el-button>
            <el-button type="warning" size="small" @click="viewPositionPacking()">站位领料单</el-button>
          </template>
        </avue-crud>
      </el-col>
      <el-col :span="11">
        <el-tabs type="border-card" style="margin: 10px" v-if="isShowDetailTable">
          <el-tab-pane label="SMT站位表详情">
            <avue-crud
              :option="detailOption"
              :table-loading="detailLoading"
              :data="detailData"
              v-model="detailForm"
              :permission="permissionList"
              :before-open="beforeDetailOpen"
              :before-close="beforeDetailClose"
              :page.sync="detailPage"
              ref="detailCrud"
              @row-del="rowDetailDel"
              @row-save="rowDetailSave"
              @row-update="rowDetailUpdate"
              @selection-change="selectionDetailChange"
              @refresh-change="detailRefreshChange"
              @current-change="currentDetailChange"
              @size-change="sizeDetailChange"
            >
              <template slot="infoForm">
                <avue-crud ref="infoCurd" @row-save="handleRowSave" :page.sync="infoPage" :option="infoOption" :data="infoData" v-model="infoForm">
                  <template slot="menu" v-if="delBtnIsShow">
                    <el-button type="text" size="small" icon="el-icon-delete" @click="handleRowDelete">删 除 </el-button>
                  </template>
                </avue-crud>
              </template>
              <template slot="menuLeft">
                <el-button v-if="permission.smttable_delete && this.params['tableId']" type="danger" size="small" icon="el-icon-delete" @click="detailHandleDelete"
                  >删 除
                </el-button>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog append-to-body :close-on-click-modal="false" title="站位领料单据" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <avue-crud
        :option="sheetOption"
        :table-loading="sheetLoading"
        :data="sheetData"
        :page.sync="sheetPage"
        v-model="form"
        :search.sync="sheetSearch"
        ref="Crud"
        @search-change="searchSheetChange"
        @current-change="currentSheetChange"
        @refresh-change="refreshSheetChange"
        @size-change="sizeSheetChange"
        @search-reset="searchSheetReset"
      >
        <template slot="menuLeft">
          <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport()">导 出</el-button>
        </template>
        <template slot="workOrderNoSearchLabel"> <span style="color: #f56c6c; margin-right: 4px">*</span><span>工单号</span> </template>
      </avue-crud>
    </el-dialog>
    <export-excel
      :visible="exprotVisible"
      :option="sheetOption"
      :page="sheetPage"
      :data="exportData"
      :loading="sheetLoading"
      name="站位领料单据"
      @selectData="handleSelectData"
      @close="handleClose"
    ></export-excel>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getTrackList,
  addTrack,
  updateTrack,
  removeTrack,
  getTrackDetail,
  verifyMachineCodeOrPartNo,
  getSelectedProduct,
  getTrackSheetList
} from '@/api/product/smttable';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportExcel from '@/components/export-excel';
export default {
  components: {
    CommonModalTemplate,
    exportExcel
  },
  data() {
    return {
      form: {},
      str: '',
      smtTable: false,
      showDialog: false,
      sheetLoading: false,
      exprotVisible: false,
      partType: '', //编码类型
      partOption: [],
      machineCode: '', //机台编码
      detailForm: {},
      query: {},
      cloneForm: {},
      sheetQuery: {},
      sheetSearch: {},
      loading: true,
      detailLoading: false,
      smttableId: '', //站位表ID
      searchPartNos: '', //产品编码
      params: {}, //详情表参数
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      infoPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      sheetPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      delBtnIsShow: false,
      timer: new Date().getTime(),
      tableOption: {},
      selectionList: [],
      selectionDetailList: [],
      detailData: [], //详情数据
      sheetData: [],
      exportData: [],
      sheetOption: {
        height: 'calc(100vh - 370px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        menu: false,
        refreshBtn: false,
        filterBtn: false,
        columnBtn: false,
        searchBtn: false,
        addBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            type: 'search',
            search: true,
            hide: true,
            slot: true,
            rules: [
              {
                required: true,
                message: '请输入工单号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openWorkOrderModal();
            }
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '物料类别',
            prop: 'partCategoryName'
          },
          // {
          //   label: '物料规格',
          //   prop: 'partCategory'
          // },
          {
            label: '工单所需总量',
            prop: 'workOrderUsageQuantity'
          },
          {
            label: '机台',
            prop: 'machineCode'
          },
          {
            label: '站号',
            prop: 'trackNo'
          },
          {
            label: '位号',
            prop: 'positionNo'
          },
          {
            label: '用量',
            prop: 'usageQuantity'
          },
          {
            label: '替代物料',
            prop: 'replacePartNos'
          },
          {
            label: '替代比例',
            prop: 'replacePartRates'
          },
          {
            label: '替代用量',
            prop: 'replacePartUsageQuantity'
          }
        ]
      },
      detailOption: {
        height: 'calc(100vh - 370px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        addBtn: false,
        editBtn: true,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '站号',
            prop: 'trackNo',
            rules: [
              {
                required: true,
                message: '请输入站号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '飞达规格',
            prop: 'feederSpecRequired'
            // dicUrl: '/api/blade-system/dict/dictionary?code=feeder_spec',
            // type: 'select',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            // rules: [
            //   {
            //     required: true,
            //     message: '请输入飞达规格',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            label: '产品编码',
            prop: 'partNos',
            type: 'select',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请输入产品编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料料号',
            prop: 'partNo',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入物料料号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartModal();
            }
          },
          {
            label: '物料规格',
            prop: 'partModel',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入物料规格',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '机台号',
            prop: 'machineCode',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入机台号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '位号',
            prop: 'positionNo',
            rules: [
              {
                required: true,
                message: '请输入位号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '用量',
            prop: 'quantity',
            type: 'number',
            precision: 2,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入用量',
                trigger: 'blur'
              }
            ]
          }
        ],
        group: [
          {
            label: '替代料',
            prop: 'equipmentInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                labelWidth: 0,
                label: '',
                prop: 'info',
                span: 24,
                hide: true,
                formslot: true
              }
            ]
          }
        ]
      }, //详情配置
      option: {
        height: 'calc(100vh - 450px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        labelWidth: 130,
        selection: true,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        column: [
          {
            label: '站位表类型', //SMT/AI
            prop: 'tableType',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=table_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入站位表类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '面向', //， TOP面, BOTTOM面
            prop: 'side',
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=side_type',
            rules: [
              {
                required: true,
                message: '请输入面向',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '站位表编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入站位表编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '贴片程序名',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入贴片程序名',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '机台号',
            prop: 'machineCode',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入机台号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openMachineCode();
            }
          },
          {
            label: '产品编码', //，可以多个，‘，’分隔，供详情选择产品时过滤使用
            prop: 'partNos',
            type: 'search',
            disabled: true,
            search: true,
            searchType: 'input',
            rules: [
              {
                required: true,
                message: '请输入产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: async () => {
              let params = this.form.partNos.split(',');
              let res = await getSelectedProduct(params);
              let selectedData = res.data.data;
              this.openProductModal(selectedData);
            }
          }
        ]
      },
      infoOption: {
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        filterBtn: false,
        delBtn: false,
        indexLabel: '序号',
        column: [
          {
            label: '料号',
            prop: 'partNo',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请输入料号',
                trigger: 'blur'
              }
            ],
            span: 8
          },
          {
            label: '替代比例',
            prop: 'rate',
            span: 8,
            value: 1,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入替代比例',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              let value = 0;
              if (val) {
                value = val * this.detailForm.quantity || 0;
              }
              this.infoForm.usage = value;
            }
          },
          {
            label: '用量',
            prop: 'usage',
            span: 8,
            disabled: true,
            value: 0
          }
        ]
      },
      infoData: [],
      infoForm: {},
      data: [],
      isShowDetailTable: false
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      this.isShowDetailTable = true;
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.smttable_add, false),
        viewBtn: this.vaildData(this.permission.smttable_view, false),
        delBtn: this.vaildData(this.permission.smttable_delete, false),
        editBtn: this.vaildData(this.permission.smttable_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    detailIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.trackId);
      });
      return ids.join(',');
    }
  },
  methods: {
    openCommonModal(partType) {
      const url = partType ? `/api/mes-admin/part-master/page?semifinished=true` : '/api/mes-admin/part-master/page?materialAndSemifinished=true';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息（双击进行选择）',
        titleInfo: 'infoForm',
        url,
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true,
            minWidth: 150
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            width: 150
          },
          {
            label: '物料型号',
            prop: 'partModel',
            width: 150
          },
          {
            label: '描述',
            prop: 'description',
            width: 150
          },
          {
            label: '版本',
            prop: 'revision',
            width: 150
          }
        ]
      };
    },
    rowSave(row, done, loading) {
      row['partNames'] = this.form.partNames;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDetailSave(row, done, loading) {
      row['tableId'] = this._get(this.params, 'tableId', '');
      row['replacePartNo'] = JSON.stringify(this.infoData);
      addTrack(row).then(
        () => {
          this.onDetailLoad(this.detailPage, this.params);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      verifyMachineCodeOrPartNo({
        tableId: row.id,
        originMachineCode: this.cloneForm.machineCode,
        newMachineCode: row.machineCode,
        originPartNos: this.cloneForm.partNos,
        newPartNos: row.partNos
      }).then((res) => {
        if (res.data.code === 200) {
          update(row).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
            },
            (error) => {
              loading();
              console.log(error);
            }
          );
        }
      });
      done();
    },
    rowDetailUpdate(row, index, done, loading) {
      row['tableId'] = this._get(this.params, 'tableId', '');
      row['id'] = row['trackId'];
      row['replacePartNo'] = JSON.stringify(this.infoData);
      updateTrack(row).then(
        () => {
          this.onDetailLoad(this.detailPage, this.params);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    rowDetailDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeTrack(row.trackId);
        })
        .then(() => {
          this.onDetailLoad(this.detailPage, this.params);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    viewPositionPacking() {
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一条数据');
        return;
      }
      this.sheetSearch = {};
      let row = this.selectionList[0];
      this.sheetQuery = {
        tableId: row.id
      };
      this.onSheetLoad(this.sheetQuery, this.sheetQuery);
      this.showDialog = true;
    },
    handleExport() {
      if (!this.sheetSearch.workOrderNo) {
        this.$message({
          type: 'warning',
          message: '请先选择工单'
        });
        return;
      }
      this.exportData = this.sheetData;
      this.exprotVisible = true;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 详情删除
     */
    detailHandleDelete() {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeTrack(this.detailIds);
        })
        .then(() => {
          this.onDetailLoad(this.detailPage, this.params);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.detailCrud.toggleSelection();
        });
    },
    handleRowSave(row, done, loading) {
      this.infoData.push(row);
      done();
    },
    handleRowDelete({ $index }) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.infoData.splice($index, 1);
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          this.cloneForm = this._cloneDeep(res.data.data);
        });
      }
      if (['add', 'edit'].includes(type)) {
        this.smtTable = true;
      }
      done();
    },
    beforeDetailOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getTrackDetail(this.detailForm.trackId).then((res) => {
          this.detailForm = res.data.data;
          this.infoData = JSON.parse(res.data.data.replacePartNo) || [];
        });
      }
      if (['add', 'edit'].includes(type)) {
        this.smtTable = false;
        this.detailForm['machineCode'] = this.machineCode;
        this.$nextTick(() => {
          this.detailOption.column[2].dicData = this.partOption;
        });
      }
      this.delBtnIsShow = type === 'edit';
      this.infoOption.addBtn = type === 'edit';
      done();
    },
    beforeDetailClose(done, type) {
      this.infoData = [];
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchSheetReset(params, done) {
      delete this.sheetQuery.workOrderId;
      this.onSheetLoad(this.sheetPage, this.sheetQuery);
      done();
    },
    searchSheetChange(params, done) {
      this.sheetPage.currentPage = 1;
      this.onSheetLoad(this.sheetPage, this.sheetQuery);
      done();
    },

    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
      this.rowClick(list[len]);
    },
    /**
     * 详情选择按钮
     */
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    selectionDetailClear() {
      this.selectionDetailList = [];
      this.$refs.detailCrud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.onDetailLoad(this.detailPage, this.params);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.onDetailLoad(this.detailPage, this.params);
    },
    currentSheetChange(currentPage) {
      this.sheetPage.currentPage = currentPage;
      this.onSheetLoad(this.sheetPage, this.sheetQuery);
    },
    sizeSheetChange(pageSize) {
      this.sheetPage.pageSize = pageSize;
      this.onSheetLoad(this.sheetPage, this.sheetQuery);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    refreshSheetChange() {
      this.onSheetLoad(this.sheetPage, this.sheetQuery);
    },
    /**
     * 详情刷新按钮
     */
    detailRefreshChange() {
      this.onDetailLoad(this.detailPage, this.params);
    },

    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    onSheetLoad(page, params = {}) {
      this.sheetLoading = true;
      getTrackSheetList(page.currentPage, page.pageSize, Object.assign(params, this.sheetQuery)).then((res) => {
        const data = res.data.data;
        this.sheetPage.total = data.total;
        this.sheetData = this._orderBy(data.records, ['partNo'], ['asc']);
        this.exportData = this.sheetData;
        this.sheetLoading = false;
      });
    },

    /**
     * 查询站位表详情
     */
    onDetailLoad(page, params = {}) {
      this.detailLoading = true;
      getTrackList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data;
        this.detailData = data.records;
        this.detailPage.total = data.total;
        this.detailLoading = false;
        this.selectionDetailClear();
      });
    },
    /**
     * 对产品编码拆解组装
     */
    splitPartNos(str) {
      let arr = str.split(',');
      return this._map(arr, (item) => {
        return {
          label: item,
          value: item
        };
      });
    },

    handleSelectData(val) {
      let current = 1;
      let pageSize = this.sheetPage.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.sheetPage.currentPage;
      }
      const page = {
        currentPage: current,
        pageSize
      };
      this.onSheetLoad(page);
    },

    handleClose(val) {
      this.exprotVisible = false;
      this.sheetData = this.exportData.splice(0, this.sheetPage.pageSize);
    },

    /**
     * 单击事件
     */
    rowClick(row) {
      this.detailOption.addBtn = true;
      this.smttableId = this._get(row, 'id');
      this.searchPartNos = this._get(row, 'searchPartNos');
      this.partOption = this.splitPartNos(this._get(row, 'partNos'));
      this.machineCode = this._get(row, 'machineCode');
      this.params = {
        tableId: this._get(row, 'id')
      };
      this.onDetailLoad(this.detailPage, this.params);
    },

    /**
     * 模态框回调
     */
    getSelectedRows(rowData, titleInfo) {
      switch (titleInfo) {
        case 'machineInfo':
          this.form['machineCode'] = this.strSplit(rowData, 'code');
          break;
        case 'productInfo':
          this.form['partNos'] = this.strSplit(rowData, 'partNo');
          this.form['partNames'] = this.strSplit(rowData, 'name');
          break;
        case 'partInfo':
          this.$set(this.detailForm, 'partNo', rowData.partNo);
          this.$set(this.detailForm, 'partModel', rowData.partModel);
          break;
        case 'infoForm':
          this.$set(this.infoForm, 'partNo', rowData.partNo);
          this.$set(this.infoForm, 'partModel', rowData.partModel);
          break;
        case 'workOrderModal':
          this.sheetSearch.workOrderNo = rowData.orderNo;
          this.sheetSearch.workOrderId = rowData.id;
          this.sheetQuery.workOrderId = rowData.id;
          this.sheetPage.currentPage = 1;
          this.onSheetLoad(this.sheetPage, this.sheetQuery);
          this.break;
        default:
          break;
      }
    },
    /**
     * 字符串逗号拼接
     */
    strSplit(rows, prop) {
      let params = [];
      this._forEach(rows, (item) => {
        params.push(item[prop]);
      });
      return String(params);
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    openWorkOrderModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'workOrderModal';
      this.tableOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: `/api/mes-product/work-order/page?partNos=${this._get(this.selectionList, '[0].partNos', '')}`,
        isPage: true,
        index: false,
        titleInfo: 'workOrderModal',
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input'
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            searchType: 'input'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName',
            search: true,
            searchType: 'input'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          }
        ]
      };
    },
    /**
     * 选择物料模态框
     */
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息（双击进行选择）',
        url: `/api/mes-admin/part-master/page?partType=MATERIAL`,
        isPage: true,
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'partInfo',
        columnDefs: [
          {
            label: '类别',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          },
          {
            label: '仓库物料类别',
            prop: 'partType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          }
        ]
      };
    },

    /**
     * 选择产品编码模态框
     */
    openProductModal(selectedData) {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息',
        url: '/api/mes-admin/partmaster/query-page-part-master?semifinished=true',
        isPage: true,
        // noPageParams: true,
        mothod: 'get',
        selection: true,
        rowSelectionType: 'multiple',
        titleInfo: 'productInfo',
        selectOption: {
          isMark: true,
          data: this.form.partNos.split(','),
          prop: 'partNo',
          selectedData: selectedData || []
        },
        columnDefs: [
          {
            label: '类别',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          },
          {
            label: '仓库物料类别',
            prop: 'partType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          }
        ]
      };
    },
    /**
     * 选择机台编码模态框
     */
    openMachineCode() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择机台编码信息',
        url: '/api/mes-product/ems-equipment/list?categoryCode=MACHINE,AI',
        isPage: false,
        noPageParams: true,
        rowSelectionType: 'multiple',
        mothod: 'post',
        selectOption: {
          isMark: true,
          data: this.form.machineCode.split(','),
          prop: 'code'
        },
        titleInfo: 'machineInfo',
        columnDefs: [
          {
            label: '类型',
            prop: 'equipmentType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            search: true
          },
          {
            label: '子类型',
            prop: 'subType'
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '用途',
            prop: 'remarks'
          },
          {
            label: '负责人',
            prop: 'principalName'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          }
        ]
      };
    },
    getUseCount({ subsRate }) {
      if (this.selectionBomDetailList.length) {
        return Number(this.selectionBomDetailList[0].unitQty) * subsRate;
      }
      return 0;
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-informationLabel {
  .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
